//
//  SmallDecisionsPromptViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/6/14.
//

#import "SmallDecisionsPromptViewController.h"
typedef enum : NSUInteger {
    
    SmallDecisionsPromptModalPresent,
    SmallDecisionsPromptModalDismiss

} SmallDecisionsPromptModalType;

@interface SmallDecisionsPromptModalTransition ()<UIViewControllerAnimatedTransitioning>

@property (nonatomic, assign) NSTimeInterval time;
@property (nonatomic, assign) SmallDecisionsPromptModalType modalType;

@end

@implementation SmallDecisionsPromptModalTransition

- (instancetype)init {
    
    self = [super init];
    if (self) {
        
        self.time = 0.35;
    }
    return self;
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
                                                                            presentingController:(UIViewController *)presenting
                                                                                sourceController:(UIViewController *)source {
    self.modalType = SmallDecisionsPromptModalPresent;
    return self;
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    
    self.modalType = SmallDecisionsPromptModalDismiss;
    return self;
}

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext {
    
    return self.time;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
    
    switch (self.modalType) {
            
        case SmallDecisionsPromptModalPresent: {
            
            [self recordProjectAlertAnimateTransitionPresent:transitionContext];
        } break;
            
        case SmallDecisionsPromptModalDismiss: {
            
            [self recordProjectAlertanimateTransitionDismiss:transitionContext];
        } break;
            
        default:
            break;
    }
}

- (void)recordProjectAlertAnimateTransitionPresent:(id<UIViewControllerContextTransitioning>)transitionContext {
    
    UIView *containerView    = [transitionContext containerView];
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *fromView = fromVC.view;
    UIView *toView   = toVC.view;
    if (!containerView || !fromView || !toView) {
        
        return;
    }
    
    toView.frame = CGRectMake(0, 0, containerView.width, containerView.height);
    toView.alpha = 0;
    [containerView addSubview: toView];
    
    NSTimeInterval time = [self transitionDuration: transitionContext];
    [UIView animateWithDuration:time animations:^{
        
        toView.alpha  = 1;
        toView.center = containerView.center;
    } completion:^(BOOL finished) {
       
        [transitionContext completeTransition: ![transitionContext transitionWasCancelled]];
    }];
}

- (void)recordProjectAlertanimateTransitionDismiss:(id<UIViewControllerContextTransitioning>)transitionContext {
    
    UIView *containerView    = [transitionContext containerView];
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *fromView = fromVC.view;
    UIView *toView   = toVC.view;
    if (!containerView || !fromView || !toView) {
        
        return;
    }
    
    NSTimeInterval time = [self transitionDuration: transitionContext];
    [UIView animateWithDuration:time animations:^{
       
        fromView.transform = CGAffineTransformMakeScale(2.0, 2.0);
        fromView.alpha = 0;
        fromView.center = containerView.center;
    } completion:^(BOOL finished) {
        
        if (![transitionContext transitionWasCancelled]) {
            
            [fromView removeFromSuperview];
        }
        [transitionContext completeTransition: ![transitionContext transitionWasCancelled]];
    }];
}

@end


@interface SmallDecisionsPromptViewController ()<UITextFieldDelegate>

@property (nonatomic, copy) NSString *promptTitle;
@property (nonatomic, strong) UILabel *promptTitleLabel;

@property (nonatomic, copy) NSString *cancelText;
@property (nonatomic, strong) UIButton *cancelButton;

@property (nonatomic, copy) NSString *sureText;
@property (nonatomic, strong) UIButton *sureButton;
@property (nonatomic, copy) NSString *placeholder;

@property (nonatomic, strong) UIImage *backgroundImage;
@property (nonatomic, strong) UIImageView *backgroundImageView;

@property (nonatomic, strong) UIDynamicAnimator *animator;

@property (nonatomic, strong) UIView *boxView;

@property (nonatomic, strong) UITextField *textField;


@property (nonatomic, strong) SmallDecisionsPromptModalTransition *modalDelegate;

@property (nonatomic, copy) void(^textFieldChangeBlock)(UITextField *textField, NSString * _Nullable text);

@property (nonatomic, copy) void(^cancelBlock)(void);
@property (nonatomic, copy) void(^sureBlock)(NSString *text);

@end

@implementation SmallDecisionsPromptViewController


+ (void)showPromptWithTitle:(NSString * _Nullable)title
                placeholder:(NSString * _Nullable)placeholder
                 cancelText:(NSString * _Nullable)cancelText
                cancelBlock:(void(^ _Nullable)(void))cancelBlock
       textFieldChangeBlock:(void(^ _Nullable)(UITextField *textField, NSString * _Nullable text))textFieldChangeBlock {
    
    SmallDecisionsPromptViewController *vc = [[SmallDecisionsPromptViewController alloc] initWithPromptTitle:title placeholder:placeholder sureText:nil sureBlock:nil cancelText:cancelText cancelBlock:cancelBlock textFieldChangeBlock:textFieldChangeBlock];
    [vc show];
}

+ (void)showPromptWithTitle:(NSString * _Nullable)title
                placeholder:(NSString * _Nullable)placeholder
                   sureText:(NSString * _Nullable)sureText
                  sureBlock:(void(^ _Nullable)(NSString *text))sureBlock
       textFieldChangeBlock:(void(^ _Nullable)(UITextField *textField, NSString * _Nullable text))textFieldChangeBlock {
    
    SmallDecisionsPromptViewController *vc = [[SmallDecisionsPromptViewController alloc] initWithPromptTitle:title placeholder:placeholder sureText:sureText sureBlock:sureBlock cancelText:nil cancelBlock:nil textFieldChangeBlock:textFieldChangeBlock];
    
    [vc show];
}

+ (void)showPromptWithTitle:(NSString * _Nullable)title
                placeholder:(NSString * _Nullable)placeholder
                   sureText:(NSString * _Nullable)sureText
                  sureBlock:(void(^ _Nullable)(NSString *text))sureBlock
                 cancelText:(NSString * _Nullable)cancelText
                cancelBlock:(void(^ _Nullable)(void))cancelBlock
       textFieldChangeBlock:(void(^ _Nullable)(UITextField *textField, NSString * _Nullable text))textFieldChangeBlock {
    
    SmallDecisionsPromptViewController *vc = [[SmallDecisionsPromptViewController alloc] initWithPromptTitle:title placeholder:placeholder sureText:sureText sureBlock:sureBlock cancelText:cancelText cancelBlock:cancelBlock textFieldChangeBlock:textFieldChangeBlock];
    
    [vc show];
}




- (instancetype)initWithPromptTitle:(NSString * _Nullable)title
                placeholder:(NSString * _Nullable)placeholder
                   sureText:(NSString * _Nullable)sureText
                  sureBlock:(void(^ _Nullable)(NSString *text))sureBlock
                 cancelText:(NSString * _Nullable)cancelText
                cancelBlock:(void(^ _Nullable)(void))cancelBlock
       textFieldChangeBlock:(void(^ _Nullable)(UITextField *textField, NSString * _Nullable text))textFieldChangeBlock {
    
    self = [super init];
    if (self) {
        self.cancelBlock = cancelBlock;
        self.sureBlock = sureBlock;
        self.promptTitle = title;
        self.placeholder = placeholder;
        self.sureText = sureText;
        self.cancelText = cancelText;
    }
    return self;
}


- (void)show {
    
    self.transitioningDelegate = self.modalDelegate;
    self.modalPresentationStyle = UIModalPresentationCustom;
    UINavigationController *lastVc = [[SmallDecisionsNavigatorManager shareInstance].navigationControllerList lastObject];
    if (lastVc) {
        
        [lastVc.viewControllers.lastObject presentViewController:self animated:YES completion:nil];
    } else {
        
        [[SmallDecisionsNavigatorManager shareInstance].mainNavigationController.viewControllers.lastObject presentViewController:self animated:YES completion:nil];
    }
    [[SmallDecisionsNavigatorManager shareInstance].navigationControllerList addObject:self];
    [[SmallDecisionsNavigatorManager shareInstance].modalDelegateList addObject: self.modalDelegate];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.animator removeAllBehaviors];
        self.boxView.hidden = NO;
        
        UIGravityBehavior *grayity = [[UIGravityBehavior alloc] initWithItems:@[self.boxView]];
        grayity.magnitude = 10.0;
        [self.animator addBehavior:grayity];
        
        UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.boxView]];
        CGPoint startPoint = CGPointMake(0, self.view.center.y + 100);
        CGPoint endPoint = CGPointMake(self.view.frame.size.width, self.view.center.y + 100);
        [collision addBoundaryWithIdentifier:@"line" fromPoint:startPoint toPoint:endPoint];
        [self.animator addBehavior:collision];
        
        UIDynamicItemBehavior *dynamicItem = [[UIDynamicItemBehavior alloc] initWithItems:@[self.boxView]];
        dynamicItem.elasticity = 0;
        dynamicItem.resistance = 2.0;
        [self.animator addBehavior:dynamicItem];
        
        [self.boxView mas_updateConstraints:^(MASConstraintMaker *make) {

            make.top.mas_equalTo(self.view.centerY + 100 - self.boxView.height);
        }];
    });
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];
    
    [self.boxView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.mas_equalTo(-self.view.centerY);
        make.width.mas_lessThanOrEqualTo(350);
        make.width.mas_greaterThanOrEqualTo(320);
        make.centerX.mas_equalTo(self.view);
    }];
    self.boxView.hidden = YES;
    
    if(self.promptTitle) {
        self.promptTitleLabel.text = self.promptTitle;
        [self.promptTitleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            
            make.height.mas_equalTo(30);
        }];
    } else {
        [self.textField mas_updateConstraints:^(MASConstraintMaker *make) {
           
            make.top.mas_equalTo(20);
        }];
    }
    
    if (self.cancelText && self.sureText) {
        
        [self.cancelButton setTitle:self.cancelText forState:UIControlStateNormal];
        [self.sureButton setTitle:self.sureText forState:UIControlStateNormal];
    } else if (!self.cancelText) {
        
        [self.sureButton setTitle:self.sureText forState:UIControlStateNormal];
        [self.cancelButton setHidden:YES];
        [self.sureButton mas_remakeConstraints:^(MASConstraintMaker *make) {
           
            make.left.mas_equalTo(0);
            make.height.mas_equalTo(50);
            make.top.mas_equalTo(self.textField.mas_bottom).mas_offset(30);
            make.width.mas_equalTo(self.boxView.mas_width);
            make.bottom.mas_equalTo(self.boxView.mas_bottom);
        }];
    } else if (!self.sureText) {
        
        [self.cancelButton setTitle:self.cancelText forState:UIControlStateNormal];
        [self.sureButton setHidden:YES];
        [self.cancelButton mas_remakeConstraints:^(MASConstraintMaker *make) {
           
            make.left.mas_equalTo(0);
            make.height.mas_equalTo(50);
            make.top.mas_equalTo(self.textField.mas_bottom).mas_offset(30);
            make.width.mas_equalTo(self.boxView.mas_width);
            make.bottom.mas_equalTo(self.boxView.mas_bottom);
        }];
    }
}

- (UIDynamicAnimator *)animator {
    
    if (!_animator) {
        
        _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    }
    return _animator;
}

- (SmallDecisionsPromptModalTransition *)modalDelegate {
    
    if (!_modalDelegate) {
        
        _modalDelegate = [[SmallDecisionsPromptModalTransition alloc] init];
        _modalDelegate.time = 0.25;
    }
    return _modalDelegate;
}

- (UIView *)boxView {
    
    if (!_boxView) {
        
        _boxView = [[UIView alloc] init];
        _boxView.backgroundColor = [UIColor whiteColor];
        _boxView.layer.cornerRadius = 5;
        _boxView.layer.masksToBounds = YES;
        [self.view addSubview:_boxView];
    }
    return _boxView;
}

- (UILabel *)promptTitleLabel {
    
    if (!_promptTitleLabel) {
        
        _promptTitleLabel = [[UILabel alloc] init];
        _promptTitleLabel.numberOfLines = 1;
        _promptTitleLabel.textColor = [UIColor blackColor];
        _promptTitleLabel.textAlignment = 1;
        _promptTitleLabel.font = SmallDecisionsSetBoldFontSize(18);
        [self.boxView addSubview:_promptTitleLabel];
        
        [_promptTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
           
            make.top.mas_equalTo(20);
            make.height.mas_equalTo(0);
            make.left.mas_equalTo(25);
            make.right.mas_equalTo(-25);
            make.centerX.mas_equalTo(self.boxView.mas_centerX);
        }];
    }
    return _promptTitleLabel;
}


- (UIButton *)cancelButton {
    
    if (!_cancelButton) {
        
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_cancelButton setTitleColor:[UIColor colorWithHexString:@"0x666666"] forState:UIControlStateNormal];
        [_cancelButton setTitleColor:[UIColor colorWithHexString:@"0x333333"] forState:UIControlStateHighlighted];
        [_cancelButton addTarget:self action:@selector(cancelButtonHandle:) forControlEvents:UIControlEventTouchUpInside];
        _cancelButton.backgroundColor = [UIColor colorWithHexString:@"0xf2f2f7"];
        [self.boxView addSubview:_cancelButton];
        
        [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
           
            make.left.mas_equalTo(0);
            make.height.mas_equalTo(50);
            make.top.mas_equalTo(self.textField.mas_bottom).mas_offset(30);
            make.width.mas_equalTo(self.boxView.mas_width).multipliedBy(0.5);
            make.bottom.mas_equalTo(self.boxView.mas_bottom);
        }];
    }
    return _cancelButton;
}

- (UIButton *)sureButton {
    
    if (!_sureButton) {
        
        _sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _sureButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_sureButton setTitleColor:SmallDecisionsBlackColor forState:UIControlStateNormal];
        [_sureButton setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
        [_sureButton addTarget:self action:@selector(otherButtonHandle:) forControlEvents:UIControlEventTouchUpInside];
        _sureButton.backgroundColor = SmallDecisionsThemeColor;
        [self.boxView addSubview:_sureButton];
        
        [_sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
           
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(50);
            make.top.mas_equalTo(self.textField.mas_bottom).mas_offset(30);
            make.width.mas_equalTo(self.boxView.mas_width).multipliedBy(0.5);
        }];
    }
    return _sureButton;
}

- (UITextField *)textField {
    if(!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.placeholder = self.placeholder;
        _textField.textColor = SmallDecisionsBlackColor;
        _textField.font = SmallDecisionsSetFontSize(14);
        _textField.delegate = self;
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 50)];
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.leftView = leftView;
        _textField.layer.borderColor = [UIColor colorWithHexString:@"0x666666"].CGColor;
        _textField.layer.borderWidth = 1;
        _textField.layer.cornerRadius = 10;
        _textField.layer.masksToBounds = YES;

        [self.boxView addSubview:_textField];
        
        [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.right.mas_equalTo(-10);
            make.height.mas_equalTo(50);
            make.top.mas_equalTo(self.promptTitleLabel.mas_bottom).mas_offset(10);
        }];
    }
    
    return _textField;
}

- (void)cancelButtonHandle:(UIButton *)btn {
    
    [self.animator removeAllBehaviors];
    
    UIGravityBehavior *grayity = [[UIGravityBehavior alloc] initWithItems:@[self.boxView]];
    grayity.magnitude = 10.0;
    [self.animator addBehavior:grayity];
    
    UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.boxView]];
    CGPoint startPoint = CGPointMake(self.view.width / 2.0 + 70, self.view.centerY + 100);
    CGPoint endPoint = CGPointMake(self.view.width / 2.0 + 100, self.view.centerY + 100);
    [collision addBoundaryWithIdentifier:@"line" fromPoint:startPoint toPoint:endPoint];
    [self.animator addBehavior:collision];
    
    UIDynamicItemBehavior *dynamicItem = [[UIDynamicItemBehavior alloc] initWithItems:@[self.boxView]];
    dynamicItem.allowsRotation = true;
    dynamicItem.angularResistance = 1;
    [self.animator addBehavior:dynamicItem];
        
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [SmallDecisionsNavigatorManager dismissViewControllerAnimated:YES completion:^{
            if(self.cancelBlock) {
                self.cancelBlock();
            }
        }];
        
    });
}

- (void)otherButtonHandle:(UIButton *)btn {
    
    [self.animator removeAllBehaviors];
    
    UIGravityBehavior *grayity = [[UIGravityBehavior alloc] initWithItems:@[self.boxView]];
    grayity.magnitude = 10.0;
    [self.animator addBehavior:grayity];
    
    UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.boxView]];
    CGPoint startPoint = CGPointMake(self.view.width / 2.0 - 100, self.view.centerY + 100);
    CGPoint endPoint = CGPointMake(self.view.width / 2.0 - 70, self.view.centerY + 100);
    [collision addBoundaryWithIdentifier:@"line" fromPoint:startPoint toPoint:endPoint];
    [self.animator addBehavior:collision];
    
    UIDynamicItemBehavior *dynamicItem = [[UIDynamicItemBehavior alloc] initWithItems:@[self.boxView]];
    dynamicItem.allowsRotation    = YES;
    dynamicItem.angularResistance = 1;
    [self.animator addBehavior:dynamicItem];
        
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SmallDecisionsNavigatorManager dismissViewControllerAnimated:YES completion:^{
            if(self.sureBlock) {
                self.sureBlock(self.textField.text);
            }
        }];
    });
}

#pragma mark UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if(self.textFieldChangeBlock) {
        self.textFieldChangeBlock(textField, textField.text);
    }
}

@end
